<template>
    <div class="chat-right-right-wrap-wrapper">
        <div class="chat-right-right-form">
            <a-form layout="horizontal">
                <a-row :gutter="15" type="flex" justify="end">
                    <a-col :xs="12" :sm="12" :md="6" :lg="10">
                        <a-form-item>
                            <a-range-picker v-model:value="queryParams.times" value-format="YYYY-MM-DD HH:mm:ss" show-time @change="handleReset()"></a-range-picker>
                        </a-form-item>
                    </a-col>
                    <a-col :xs="12" :sm="12" :md="6" :lg="8">
                        <a-form-item>
                            <a-input-search v-model:value="queryParams.keyword" placeholder="请输入关键字搜索消息" allow-clear enter-button @search="handleReset()" />
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
        </div>
        <div class="chat-right-right-wrap-item" ref="scrollRef">
            <div class="flex justify-center loading-wrap" v-if="state.loading">
                <loading-outlined />
                数据加载中...
            </div>
            <div class="flex justify-center items-center h-100" v-if="messageList.length == 0 && state.end">
                <a-empty></a-empty>
            </div>
            <div class="chat-item-list" v-for="(item, index) in messageList" :key="index" :class="`chatItem${index}`">
                <div class="chat-item-list-date">{{ item.msgtimeFormat }}</div>
                <div class="chat-item-list-left flex" v-if="item.msgfrom !== props.employee.workPhone">
                    <a-avatar shape="square" :size="40" :src="item.senderAvatar" v-if="item.senderAvatar"></a-avatar>
                    <a-avatar :size="40" v-else shape="square">
                        <template #icon><UserOutlined /></template>
                    </a-avatar>
                    <div class="flex-1">
                        <div class="chat-item-list-nick">{{ item.senderName }}</div>
                        <chat-content :item="item" :isLeft="true"></chat-content>
                    </div>
                </div>
                <div class="chat-item-list-right flex w-full justify-end" v-else>
                    <div class="flex-1">
                        <div class="chat-item-list-nick">{{ item.senderName }}</div>
                        <chat-content :item="item"></chat-content>
                    </div>
                    <a-avatar shape="square" :size="40" :src="item.senderAvatar" v-if="item.senderAvatar"></a-avatar>
                    <a-avatar :size="40" v-else shape="square">
                        <template #icon><UserOutlined /></template>
                    </a-avatar>
                </div>
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
    import { ref,  watch, reactive, PropType, nextTick } from 'vue';
    import { useInfiniteScroll } from '@vueuse/core';
    import { UserOutlined, LoadingOutlined } from '@ant-design/icons-vue';
    import { messageQuery } from '@/api/smss/chat';
    import { isNotEmpty } from '@/utils/is';
    import { toStringJSON } from 'xe-utils';
    import { selectKey } from './common';
    import chatContent from './chat-content.vue';

    const props = defineProps({
        tabId: {
            type: String,
            default: '1',
        },
        // 是否是单聊，false视为群聊
        isSingleChat: {
            type: Boolean,
            default: true,
        },
        client: {
            type: Object as PropType<any>,
            default: () => {},
        },
        employee: {
            type: Object as PropType<any>,
            default: () => {},
        },
    });

    const scrollRef = ref<any>(null);
    const messageList = ref([]);
    const state = reactive<any>({
        current: 1,
        clientId: '',
        loading: false,
        end: false,
        scrollTop: 0,
    });

    const queryParams = ref<any>({
        keyword: '',
        times: [],
    });

    watch(
        () => props.client,
        (v, oldV) => {
            console.log(v, oldV);

            if (isNotEmpty(v) && oldV[selectKey[props.tabId]] !== v[selectKey[props.tabId]]) {
                handleReset();
            }
        },
    );

    const { isLoading } = useInfiniteScroll(
        scrollRef,
        (data: any) => {
            // load more
            loadMore();
        },
        {
            distance: 20,
            direction: 'top',
            canLoadMore: () => !state.end && isNotEmpty(props.client),
        },
    );

    // 异步数据加载
    const fetchData = async current => {
        return new Promise(resolve => {
            const { tabId, isSingleChat } = props;
            const params: any = {
                current,
                isSingleChat,
                searchContent: queryParams.value.keyword,
                startTime: queryParams.value.times[0],
                endTime: queryParams.value.times[1],
            };
            const { externalUserid, userid, roomid } = props.client;
            if (isSingleChat) {
                params.recipient = tabId === '1' ? externalUserid : userid;
                params.sender = props.employee.workPhone;
            } else {
                params.roomid = roomid;
            }
            messageQuery(params).then(res => {
                const { records = [], pages, current } = res.data;
                if (pages > current) {
                    state.current++;
                }
                state.end = pages <= current;

                resolve(
                    records
                        .map(item => ({
                            ...item,
                            msgdata: toStringJSON(item.msgdata),
                        }))
                        .reverse(),
                );
            });
        });
    };

    const loadMore = async () => {
        if (state.loading) return;
        state.loading = true;
        let scrollTop = 0;
        if (scrollRef.value) {
            scrollTop = scrollRef.value.scrollHeight;
        }

        try {
            if (!isNotEmpty(props.client)) return false;
            if (state.end) return false;
            const newItems: any = await fetchData(state.current);
            console.log(newItems);
            messageList.value.unshift(...newItems);

            nextTick(() => {
                if (scrollRef.value) {
                    scrollRef.value.scrollTop = scrollRef.value.scrollHeight - scrollTop;
                }
            });
        } catch (error) {
            console.error('加载失败', error);
        } finally {
            state.loading = false;
        }
    };

    const handleReset = () => {
        state.current = 1;
        state.end = false;
        messageList.value = [];
        state.loading = false;

        loadMore();
    };

</script>

<style lang="less">
    .chat-right-right-wrap-wrapper {
        height: 100%;

        .chat-right-right-form {
            background-color: #fff;
            padding: 10px 10px 10px 0;

            :deep(.ant-form-item) {
                margin-bottom: 0;
            }
        }

        .chat-right-right-wrap-item {
            background-color: #eaecf3;
            height: calc(100% - 52px);
            overflow-y: auto;
            padding: 15px;

            .chat-item-list {
                margin-top: 10px;

                & > div {
                    &.chat-item-list-date {
                        text-align: center;
                        color: #aaa;
                        font-size: 14px;
                        width: 100%;
                        margin: 10px 0 5px;
                    }
                    .chat-item-list-nick {
                        margin-bottom: 10px;
                    }
                }
                .chat-item-list-left,
                .chat-item-list-right {
                    .content-wrap {
                        width: 100%;

                        .content {
                            display: inline-block;
                            padding: 5px 10px;
                            line-height: 24px;
                            font-size: 15px;
                            border-radius: 8px;
                            word-break: break-all;
                            cursor: pointer;
                            max-width: 60%;
                        }
                    }
                }
                .chat-item-list-left {
                    .content {
                        background-color: #fff;
                    }

                    & > .ant-avatar {
                        margin-right: 15px;
                        flex-shrink: 0;
                    }
                }
                .chat-item-list-right {
                    .content {
                        background-color: #95ec69;
                    }

                    & > .ant-avatar {
                        margin-left: 15px;
                        flex-shrink: 0;
                    }

                    .chat-item-list-nick {
                        text-align: right;
                    }
                }
            }
        }
    }
</style>
